import router from "@/router"
import { useUserStore } from "@/stores/user"
import axios from "axios"
import { ElMessage } from "element-plus"
import 'element-plus/es/components/message/style/css'

// 创建请求对象
export const request = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    ElMessage.error(error.response?.data.message || '网络错误')
    const userStore = useUserStore()
    // token失效
    if (error.response?.status === 401) {
      userStore.clearUserInfo()
      // 跳转到登录页
      router.push('/login')
    }

    return Promise.reject(error)
  }
)
